import React from 'react';
import debounce from '@/utils/debounce';

type Props = {
  children(width: number): any;
}

type State = {
  width: number;
}

class Resize extends React.PureComponent<Props, State> {
  static defaultProps = {
    children: () => null
  }

  static evtType = 'resize';

  state: State = {
    width: 0
  }

  private el: any = null;

  componentDidMount() {
    this.setWidth();
    window.addEventListener(
      Resize.evtType, this.onResize
    );
  }

  componentWillUnmount() {
    window.removeEventListener(
      Resize.evtType, this.onResize
    );
  }

  private setWidth = () => {
    this.setState({ width: this.el.clientWidth });
  }

  private onResize = debounce(() => this.setWidth());

  render() {
    return (
      <div ref={(e: HTMLDivElement) => this.el = e}>
        {this.props.children(this.state.width)}
      </div>
    );
  }
}

export default Resize;
